package com.example.cabinetcontrol.util;

import android.content.Context;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class CommonUtils {

    static Context context;

    public CommonUtils(Context context) {
        this.context = context;
    }

    public static String decode(String text) {
        byte[] encoded = Base64.decode(text, Base64.DEFAULT);
        return new String(encoded);
    }

    public static boolean xorVerify(byte[] bs) {
        byte temp = 0x00;
        int index = bs.length - 1;
        for (int i = 2; i < index; i++) {
            temp = (byte) (temp ^ bs[i]);
        }
        writeLog((temp & 0xff)+"  校验位");
        return (byte)(temp & 0xff) == bs[index];
    }

    public static boolean crc8(byte[] bs) {
        byte temp = 0x00;
        int index = bs.length - 1;
        for (int i = 0; i < index; i++) {
            temp = (byte) (temp ^ bs[i]);
        }
        return (byte)(temp & 0xff) == bs[index];
    }

    public static boolean crcVerify(byte[] bs) {
        byte temp = 0x00;
        int index = bs.length - 3;
        for (int i = 1; i < bs.length - 3; i++) {
            temp += bs[i];
        }
        return (byte) (temp & 0xFF) == bs[index];
    }

    public static char[] hex(byte b) {
        // 得到高四位
        int hi = ((b >> 4) & 0x0F);
        // 得到低四位
        int lo = (b & 0x0F);
        char[] hex = new char[2];
        // 如果高四位是大于9的，将其转换成字符a-z, 最后要将得到的转换成字符（char）类型，不然得到的是二进制数
        hex[0] = hi > 9 ? (char) (hi - 10 + 'A') : (char) (hi + '0');
        hex[1] = lo > 9 ? (char) (lo - 10 + 'A') : (char) (lo + '0');
        return hex;
    }

    /**
     * 构造上位机发指令至锁板的byte数组
     * @param addr    锁板地址：00H 通讯访问时锁板地址。(一个柜有两块锁板01－02)
     * @param command 指令：d1H 开锁；d2H 查询状态
     * @param number    锁号：柜门号，（01H－0cH）一块板一共12位，如果是查询状态，应该填00H
     * @return byte[]
     */
    public static byte[] commandBytes(int addr ,byte command, int number) {
        byte[] bs = new byte[11];
        bs[0] = 0x5C;
        bs[1] = (byte) 0xC5;
        bs[2] = 0x05;
        bs[3] = (byte)addr;
        bs[4] = command;
        bs[5] = (byte)number;
        bs[6] = 0x00;
        bs[7] = 0x00;
        for (int i = 2; i < 8; i++) {
            bs[8] = (byte) (bs[8] ^ bs[i]);
        }
        bs[9] = 0x0D;
        bs[10] = 0x0A;
        return bs;
    }


    /**
     * 售卖柜大门
     * @param addr    锁板地址：00H 通讯访问时锁板地址。(一个柜有两块锁板01－02)
     * @param command 指令：d1H 开锁；d2H 查询状态
     * @param door    锁号：柜门号，（01H－0cH）一块板一共12位，如果是查询状态，应该填00H
     * @return byte[]
     */
    public static byte[] commandBytes(byte addr, byte command, byte door,int doortime) {
        byte[] bs = new byte[12];
        bs[0] = 0x5c;
        bs[1] = (byte) 0xC5;
        bs[2] = 0x06;
        bs[3] = addr;
        bs[4] = command;
        bs[5] = door;
        bs[6] = (byte)doortime;
        bs[7] = 0x00;
        bs[8] = 0x00;
        for (int i = 2; i < 9; i++) {
            bs[9] = (byte) (bs[9] ^ bs[i]);
        }
        bs[10] = 0x0D;
        bs[11] = 0x0A;
        return bs;
    }

    //CRC16
    public static String Make_CRC(byte[] data) {
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];
        }
        int len = buf.length;
        int crc = 0xFFFF;//16位
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of
// crc
            } else {
                crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc
            }
            for (int i = 8; i != 0; i--) { // Loop over each bit
                if ((crc & 0x0001) != 0) { // If the LSB is set
                    crc >>= 1; // Shift right and XOR 0xA001
                    crc ^= 0xA001;
                } else
                    // Else LSB is not set
                    crc >>= 1; // Just shift right
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
        }
        return c;
    }



    /**
     * 将String转换为byte[]
     *
     * @param s String
     * @return byte[]
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }


    public static String byteToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length);
        String sTemp;
        for (byte aByte : bytes) {
            sTemp = Integer.toHexString(0xFF & aByte);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static void writeLog(String message) {
        writeLog("log", message);
    }

    public static void writeLog(String filename, String message) {
        File myDir = new File(Environment.getExternalStorageDirectory().getPath() + "/sc");
        if (!myDir.exists()) {

            if (!myDir.mkdirs()) {
                return;
            }
        }
        File file = new File(myDir, filename + ".txt");
        BufferedWriter fout;
        try {
            fout = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true),"UTF-8"));
            fout.write(message + "\n");
            fout.close();

//            //保存日志时间超过两天则返回ture，然后删除日志文件
//            if(PreferencesUtils.getString(context,"clearFileTime")==null){
//                PreferencesUtils.putString(context, "clearFileTime", TimeUtils.getTime());
//            }
//            else {
//                if(TimeUtils.timeDifference(PreferencesUtils.getString(context,"clearFileTime"))){
//                    file.delete();//删除文件
//                    PreferencesUtils.putString(context, "clearFileTime", TimeUtils.getTime());//删除后更新时间
//                }
//            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("Context","删除文件出错："+e);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("Context","删除文件出错："+e);
        }
    }


    public static long getFolderSize(File file){

        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++)
            {
                if (fileList[i].isDirectory())
                {
                    size = size + getFolderSize(fileList[i]);

                }else{
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return size/1048576;
        return size;
    }

}
